package com.interview.controller;

import ch.qos.logback.classic.Logger;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.interview.entity.AnswerSubmitRequest;
import com.interview.entity.QuesUser;
import com.interview.entity.param.SelectQuesUserParam;
import com.interview.result.AnswerScoreResult;
import com.interview.result.Result;
import com.interview.result.ResultCode;
import com.interview.service.QuesUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author JiangYingbo
 */
@Tag(name = "用户答题管理", description = "用户答题管理")
@RestController
@RequestMapping("/quesUser")
public class QuesUserController {
    @Autowired
    private QuesUserService quesUserService;
    @Autowired
    private ChatController chatService;
    // 初始化 Logger
    private static final Logger log = (Logger) LoggerFactory.getLogger(QuesUserController.class);



    @Operation(summary = "查询用户答题列表")
    @PostMapping("/quesUserList")
    public Result quesUserList(HttpSession session,
                               @RequestBody SelectQuesUserParam param) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return new Result(401, "请求失败", "请先登录！");
        }
        param.setUserId(userId);
        return new Result(quesUserService.selectQuesUserList(param));
    }

    @Operation(summary = "根据id删除用户答题")
    @GetMapping("/deleteById/{quesUserId}")
    public Result deleteById(HttpSession session,
                             @PathVariable("quesUserId") Integer quesUserId) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return new Result(401, "请求失败", "请先登录！");
        }
        return new Result(quesUserService.deleteQuesUserByUserId(quesUserId));
    }

    @Operation(summary = "根据id查询用户答题")
    @GetMapping("/quesUserInfo/{quesUserId}")
    public Result quesUserInfo(HttpSession session,
                               @PathVariable("quesUserId") Integer quesUserId) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return new Result(401, "请求失败", "请先登录！");
        }
        return new Result(quesUserService.quesUserInfo(quesUserId));
    }

    @Operation(summary = "新增问题记录")
    @PostMapping("/insertQuesUser")
    public Result insertQuesUser(@RequestBody QuesUser quesUser,
                                 HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return new Result(401, "请求失败", "请先登录！");
        }
        quesUser.setUserId(userId);
        quesUserService.insertQuesUser(quesUser);
        return new Result(ResultCode.SUCCESS, "添加成功！");
    }

//    @Operation(summary = "提交回答")
//    @PostMapping("/submitAnswer/{quesUserId}")
//    public Mono<Result> submitAnswer(@PathVariable("quesUserId") Integer quesUserId,
//                                     @RequestBody AnswerSubmitRequest request) {
//        // 1. 参数校验
//        if (StringUtils.isBlank(request.getUserReply())) {
//            return Mono.just(new Result(ResultCode.FAILED, "回答不能为空"));
//        }
//
//        // 2. 调用大模型评分服务并处理结果
//        return chatService.chat(request.getUserReply())
//                .collectList() // 将 Flux 收集为一个包含所有元素的列表
//                .flatMap(results -> {
//                    // 3. 将响应结果转换为 AnswerScoreResult
//                    AnswerScoreResult scoreResult = convertToAnswerScoreResult(results);
//
//                    //更新数据库
//                    QuesUser quesUser=quesUserService.quesUserInfo(quesUserId);
//                    quesUser.setUserReply(request.getUserReply());
//                    quesUser.setSuggestion(scoreResult.getReason().replace("think>", ""));
//                    quesUser.setPoint(scoreResult.getScore());
//                    quesUser.setQuesStatus(1);
//
//                    // 4. 更新数据库（假设 updateUserReply 返回 Mono<Void>）
//                    return quesUserService.updateQuesUser(quesUser)
//                            .thenReturn(new Result(ResultCode.SUCCESS, scoreResult));
//
//                })
//                .onErrorResume(e -> {
//
//                    log.error("评分失败", e);
//                    return Mono.just(new Result(ResultCode.FAILED, "评分失败，请重试"));
//                });
//    }
//
//    private AnswerScoreResult convertToAnswerScoreResult(List<String> results) {
//        // 将大模型返回的结果列表转换为 AnswerScoreResult 对象
//        StringBuilder responseBuilder = new StringBuilder();
//        results.forEach(responseBuilder::append);
//
//        // 解析响应内容并创建 AnswerScoreResult 对象
//        AnswerScoreResult result = new AnswerScoreResult();
//        // 假设大模型返回的格式包含分数和原因
//        // 这里需要根据实际返回格式进行解析
//        result.setScore(extractScore(responseBuilder.toString()));
//        result.setReason(extractReason(responseBuilder.toString()));
//        return result;
//    }
//
//    private int extractScore(String response) {
//        // 从响应中提取分数的逻辑
//        // 示例：假设分数是返回内容的前几个字符
//        try {
//            return Integer.parseInt(response.substring(0, 2).trim());
//        } catch (Exception e) {
//            return 0; // 默认分数
//        }
//    }
//
//    private String extractReason(String response) {
//        // 从响应中提取原因的逻辑
//        // 示例：假设原因是返回内容的剩余部分
//        return response.substring(2).trim();
//    }

}
